package cn.bonoon.kernel;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import java.text.ParseException;
import org.springframework.util.StringUtils;

public class KernelTimestampEditor extends PropertyEditorSupport {

	    private final SimpleDateFormat dateFormat;
	    public KernelTimestampEditor(){
	    	dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    	dateFormat.setLenient(false);
	    }
	 
	    public void setAsText(String text) throws IllegalArgumentException {
	        if (!StringUtils.hasText(text)) {
	            setValue(null);
	        } else {
	            try {
	                setValue(new Timestamp(this.dateFormat.parse(text).getTime()));
	            } catch (ParseException ex) {
	                throw new IllegalArgumentException("Could not parse date: "
	                        + ex.getMessage(), ex);
				}
	        }
	    }
	 
	    public String getAsText() {
	        Timestamp value = (Timestamp) getValue();
	        return ((value != null) ? this.dateFormat.format(value) : "");
	    }
}